<?php


namespace App\Http\Controllers\Admin;


use App\DTOS\Admin\WhiteListDTO;
use App\Models\Customer;
use App\Models\Game\Server;
use App\Models\Game\WhiteList;
use App\Services\Game\WhiteListService;
use App\Utils\ResponseUtil;

class WhiteListController
{
    private WhiteListService $WhiteListService;

    /**
     * WhiteListController constructor.
     * @param WhiteListService $WhiteListService
     */
    public function __construct(WhiteListService $WhiteListService)
    {
        $this->WhiteListService = $WhiteListService;
    }

    public function add()
    {
        $input = request()->all();
        $inserts = [];
        $game_area = data_get($input,'serverId');
        $comment = data_get($input,'comment');
        $customerIds = explode(',',data_get($input,'customerIds'));
        if ($game_area!='all'){
            foreach($customerIds as $item){
                $inserts[] = [
                    'game_area'=>$game_area,
                    'customer_id'=>trim($item),
                    'comment'=>$comment,
                    'created_at'=>date('Y-m-d H:i:s'),
                ];
            }
        } else {
            $serverIds = Server::query()->get()->pluck('server_id')->toArray();
            foreach($serverIds as $serverId){
                foreach($customerIds as $item){
                    $inserts[] = [
                        'game_area'=>$serverId,
                        'customer_id'=>trim($item),
                        'comment'=>$comment,
                        'created_at'=>date('Y-m-d H:i:s'),
                    ];
                }
            }
        }

        WhiteList::query()->insert($inserts);
        return ResponseUtil::success();
    }

    public function paginate()
    {
        $DTO = new WhiteListDTO(request()->all());
        $paginate = $this->WhiteListService->paginate($DTO);
        $data = $paginate->items();
        $customerIds = collect($data)->pluck('customer_id')->toArray();
        $customerList = Customer::query()->whereIn('id',$customerIds)->get();
        foreach($data as &$datum){
            $customer = collect($customerList)->where('id',$datum['customer_id'])->first();
            $datum['customer'] = $customer;
            $datum['customer_id'] = (string)$datum['customer_id'];
        }
        $res = [];
        $res['code'] = 0;
        $res['count'] = $paginate->total();
        $res['data'] = $data;
        return ResponseUtil::json($res);
    }

    public function delete()
    {
        $ids = request()->get('ids',[]);
        WhiteList::query()->whereIn('id',$ids)->delete();
        return ResponseUtil::success();
    }

}
